package com.thx.appserver.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;

import com.thx.common.struts2.Struts2Utils;
import com.thx.common.util.AppContext;

public class FileUploadUtil {
	static Logger logger = Logger.getLogger(FileUploadUtil.class);

	public static void uploadFile(String fileType, String fileUploadFileName,
			File fileUpload) {
		String extName = "";
		String newFileName = "";
		String nowTimeStr = "";
		SimpleDateFormat sDateFormat;
		String back = "";
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			String savePath =null;
			savePath =	ServletActionContext.getServletContext()
					.getRealPath("");
			String packageString = fileType.replaceAll(",", "-");
			packageString = packageString.replaceAll("\\.", "");
			packageString = packageString.trim();
			savePath = savePath + "/" + packageString + "/";// WebRoot目录下的file文件
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Charset", "utf-8");
			response.setHeader("Cache-Control", "no-cache");
			Random r = new Random();
			int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; 
			sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); 
			nowTimeStr = sDateFormat.format(new Date()); //
			if (fileUploadFileName.lastIndexOf(".") >= 0) {
				extName = fileUploadFileName.substring(fileUploadFileName
						.lastIndexOf("."));// 文件类型
			}
			newFileName = nowTimeStr + rannum + extName; // 保存的文件名
			String filePath = savePath + newFileName; // 文件绝对路径名
			filePath = filePath.replace("\\", "/");
			String tishi = fileUploadFileName + "上传成功！";
			if (checkFileType(fileType, extName)) {
				FileUtils.copyFile(fileUpload, new File(filePath));
				// back+=tishi + ",";
				// back+=filePath + ",";
				back += packageString + "/" + newFileName;
			} else {
				back += "文件格式不对";
			}
			response.getWriter().write(back);
			// Struts2Utils.renderHtml(back);
		} catch (IOException e) {
			logger.error("", e);
			// Struts2Utils.renderText("error");
			try {
				response.getWriter().write("error");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	public static boolean checkFileType(String fileType, String extName) {
		boolean flag = false;
		if (extName != null && fileType != null) {
			String[] fileTypes = fileType.split(",");
			for (int i = 0; i < fileTypes.length; i++) {
				flag = flag || extName.equalsIgnoreCase(fileTypes[i].trim());
			}
		}
		return flag;
	}
}
